//
//  ViewController.m
//  异步下载
//
//  Created by OnePiece on 15/9/9.
//  Copyright (c) 2015年 qianfeng. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableData * _data;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    //地址
    NSString * urlStr = @"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=2";
    //资源定位符
    NSURL * url = [NSURL URLWithString:urlStr];
    //创建请求对象
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    //创建网络连接对象
    NSURLConnection * connect = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    _data = [NSMutableData data];
}
#pragma mark - 协议方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"收到服务器响应，即将建立链接，下载数据");
    if ([response isKindOfClass:[NSHTTPURLResponse class]] == YES) {
        //如果协议是http响应，证明响应是正确的，打印响应的状态
        NSHTTPURLResponse * httpresponse = (id)response;
        //        NSHTTPURLResponse继承自NSURLResponse
        NSLog(@"%ld", (long)httpresponse.statusCode);
        //200成功  404 是错误，没有响应。
    }
    
    //收到响应之后，connection会自然的建立链接，下载数据。
    
//    //清空_data
//    _data.length = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"收到数据");
    //如果数据比较大，这个函数会反复调用，每次获取部分数据，数据就是参数data
    
    //将每次下载到的数据，拼接到_data中
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"数据接收完毕");
    
    NSLog(@"%s", _data.bytes);
    //解析
    NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    //存储数据  存入模型
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"下载发生错误 %@", error);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
